import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/EmptyUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/widget/LoadingWidget.dart';
import 'package:flutter_ahj_app/base/widget/NoneData.dart';

class ChoosePcnr extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    // throw UnimplementedError();
    return ChoosePcnrState();
  }
}

class ChoosePcnrState extends BaseState<YhpcViewModel, ChoosePcnr> {
  PageController _pageController;
  bool _isNext = false;
  TextEditingController _controller = TextEditingController(text: '');
  int _currentIndex = 0;
  List _pcdxList;
  List _selPcdxList = [];
  List _pcnrList = [];

  @override
  void initState() {
    _pageController = PageController(initialPage: _currentIndex);
    // TODO: implement initState
    super.initState();

    Future.delayed(Duration.zero, () {
      _getData();
    });
  }

  _getData() {
    var map = {'riskPointName': _controller.text};
    viewModel.getPcnr(map);
    viewModel.getPcnrStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          _pcdxList = [];
          _pcdxList = event['data']['records'];
        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  @override
  Widget initWidget() {
    return Scaffold(
      backgroundColor: SQColor.white,
      appBar: MTopBar(
        elevation: 0,
        title: '选择排查内容',
      ).create(),
      body: _pcdxList == null
          ? LoadingWidget()
          : _bodyView(),
    );
  }

  _bodyView() {
    return PageView.builder(
      controller: _pageController,
      physics: NeverScrollableScrollPhysics(),
      scrollDirection: Axis.horizontal,
      itemCount: 2,
      itemBuilder: (BuildContext context, int index) {
        return index == 0 ? _pcdxView() : _pcnrView();
      },
    );
  }

  //排查对象
  _pcdxView() {
    return Container(
      color: Color(0xfff6f6f6),
      child: Column(
        children: [
          Expanded(
            child: Container(
              padding: EdgeInsets.all(Dimens.dimens15),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        color: SQColor.white,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      height: Dimens.dimens50,
                      child: Row(
                        children: [
                          Expanded(
                            child: Container(
                              padding:
                                  EdgeInsets.fromLTRB(Dimens.dimens10, 0, 0, 0),
                              child: Row(
                                children: [
                                  Container(
                                    alignment: Alignment.center,
                                    width: Dimens.dimens24,
                                    height: Dimens.dimens24,
                                    decoration: BoxDecoration(
                                      color: Color(0xff165DFF),
                                      borderRadius: BorderRadius.circular(
                                          Dimens.dimens12),
                                    ),
                                    child: JText(
                                      '1',
                                      color: SQColor.white,
                                    ),
                                  ),
                                  Container(
                                    child: JText(
                                      '  选择排查对象',
                                      color: Color(0xff165DFF),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Expanded(
                            child: Container(
                              child: Row(
                                children: [
                                  Container(
                                    alignment: Alignment.center,
                                    width: Dimens.dimens24,
                                    height: Dimens.dimens24,
                                    decoration: BoxDecoration(
                                      color: Color(0xffaaaaaa),
                                      borderRadius: BorderRadius.circular(
                                          Dimens.dimens12),
                                    ),
                                    child: JText(
                                      '2',
                                      color: SQColor.white,
                                    ),
                                  ),
                                  Container(
                                    child: JText(
                                      '  选择排查内容',
                                      color: Color(0xffaaaaaa),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    _searchLayout(),
                    _pcdxList.length == 0
                        ? Container(margin: EdgeInsets.only(top: Dimens.dimens54),child: NoneData(),)
                        :  ListView.builder(
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: _pcdxList.length,
                        itemBuilder: (context, index) {
                          return InkWell(
                            onTap: () {
                              setState(() {
                                _pcdxList[index]['isSel'] =
                                    _pcdxList[index]['isSel'] == null
                                        ? true
                                        : !_pcdxList[index]['isSel'];
                                if (_pcdxList[index]['isSel']) {
                                  _selPcdxList.add(_pcdxList[index]);
                                  Map map = {
                                    'riskPointId': _pcdxList[index]['id'],
                                  };
                                  _pcnrList.add(map);
                                } else {
                                  for (var i = 0; i < _pcnrList.length; i++) {
                                    if (_pcnrList[i]['riskPointId'] ==
                                        _pcdxList[index]['id']) {
                                      _pcnrList.removeAt(i);
                                    }
                                  }
                                  _selPcdxList.remove(_pcdxList[index]);
                                }
                                if (_selPcdxList.length > 0) {
                                  _isNext = true;
                                } else {
                                  _isNext = false;
                                }
                              });
                            },
                            child: Column(
                              children: [
                                Container(
                                  decoration: BoxDecoration(
                                    color: SQColor.white,
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  padding: EdgeInsets.only(left: 10),
                                  child: Row(
                                    children: [
                                      Expanded(
                                          child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            margin: EdgeInsets.only(top: 10),
                                            child: JText(
                                              _pcdxList[index]
                                                      ['riskPointName'] ??
                                                  '',
                                              fontWeight: FontWeight.bold,
                                              fontSize: 16,
                                            ),
                                          ),
                                          Container(
                                            margin: EdgeInsets.only(top: 5),
                                            child: JText(
                                                '排查对象类型：${_pcdxList[index]['riskPointTypeName'] ?? ''}'),
                                          ),
                                          Container(
                                            margin: EdgeInsets.only(top: 5),
                                            child: JText(
                                                '场所/位置：${_pcdxList[index]['districtName'] ?? ''}'),
                                          ),
                                          Container(
                                            margin: EdgeInsets.only(
                                                top: 5, bottom: 10),
                                            child: JText(
                                                '管控责任部门：${_pcdxList[index]['orgName'] ?? ''}'),
                                          ),
                                        ],
                                      )),
                                      Checkbox(
                                        value: _pcdxList[index]['isSel'] == null
                                            ? false
                                            : _pcdxList[index]['isSel'],
                                        onChanged: (value) {
                                          setState(() {
                                            _pcdxList[index]['isSel'] =
                                                _pcdxList[index]['isSel'] ==
                                                        null
                                                    ? true
                                                    : !_pcdxList[index]
                                                        ['isSel'];
                                            if (_pcdxList[index]['isSel']) {
                                              _selPcdxList
                                                  .add(_pcdxList[index]);
                                              Map map = {
                                                'riskPointId': _pcdxList[index]
                                                    ['id'],
                                              };
                                              _pcnrList.add(map);
                                            } else {
                                              for (var i = 0;
                                                  i < _pcnrList.length;
                                                  i++) {
                                                if (_pcnrList[i]
                                                        ['riskPointId'] ==
                                                    _pcdxList[index]['id']) {
                                                  _pcnrList.removeAt(i);
                                                }
                                              }
                                              _selPcdxList
                                                  .remove(_pcdxList[index]);
                                            }
                                          });
                                          if (_selPcdxList.length > 0) {
                                            _isNext = true;
                                          } else {
                                            _isNext = false;
                                          }
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                                Container(
                                  height: 10,
                                  color: Color(0xfff6f6f6),
                                  width: double.infinity,
                                ),
                              ],
                            ),
                          );
                        }),
                  ],
                ),
              ),
            ),
          ),
          Container(
            color: SQColor.white,
            height: Dimens.dimens64,
            child: InkWell(
              onTap: () {
                if (_isNext) {
                  if (_selPcdxList.length == 0) {
                    ToastUtils.showToast('请先选择排查对象');
                    return;
                  }
                  _currentIndex = 1;
                  _pageController.animateToPage(1,
                      curve: Curves.ease,
                      duration: Duration(milliseconds: 400));
                }
              },
              child: Container(
                margin: EdgeInsets.only(
                    left: Dimens.dimens16,
                    right: Dimens.dimens16,
                    top: Dimens.dimens10,
                    bottom: Dimens.dimens10),
                color: _isNext ? Color(0xff165DFF) : SQColor.black_9B9B9B,
                child: Center(
                  child: JText(
                    '下一步',
                    color: SQColor.white,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _searchLayout() {
    return Container(
      margin: EdgeInsets.all(Dimens.dimens16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.0),
      ),
      child: Row(
        children: [
          Container(
            width: 20,
            height: 20,
            margin: EdgeInsets.only(left: 10),
            child: Icon(
              Icons.search,
              color: Color(0xffaaaaaa),
            ),
          ),
          Expanded(
            child: Container(
              height: Dimens.dimens36,
              child: TextField(
                controller: _controller,
                maxLines: 1,
                onSubmitted: (value) {
                  _getData();
                },
                decoration: InputDecoration(
                  hintText: "请输入名称搜索",
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  fillColor: Colors.white,
                  //filled = true 时为背景颜色
                  filled: true,
                  contentPadding: EdgeInsets.fromLTRB(
                      Dimens.dimens16, 0, Dimens.dimens16, 0),
                  enabledBorder: OutlineInputBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(Dimens.dimens4)), //圆角
                    borderSide: BorderSide(color: Colors.white, width: 1), //边框
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(Dimens.dimens4)), //圆角
                    borderSide: BorderSide(color: Colors.white, width: 1), //边框
                  ),
                  suffixIcon: _controller.text.length > 0
                      ? new IconButton(
                          icon: Icon(
                            Icons.close,
                            color: SQColor.per38Black,
                            size: Dimens.dimens20,
                          ),
                          onPressed: () {
                            setState(() {
                              _controller.clear();
                              _getData();
                            });
                          })
                      : null,
                ),
              ),
            ),
          ),
          Container(
            width: 1,
            color: SQColor.black_BDBDBD,
            height: Dimens.dimens16,
            margin: EdgeInsets.only(right: Dimens.dimens16),
          ),
          GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
              _getData();
            },
            child: Container(
              padding: EdgeInsets.only(right: Dimens.dimens16),
              height: Dimens.dimens48,
              alignment: Alignment.centerRight,
              child: Text("搜索",
                  style: TextStyle(
                      color: Color(0xff165DFF), fontSize: Dimens.textSize28)),
            ),
          ),
        ],
      ),
    );
  }

  // 排查内容
  _pcnrView() {
    return Container(
      color: Color(0xfff6f6f6),
      child: Column(
        children: [
          Expanded(
            child: Container(
              padding: EdgeInsets.all(Dimens.dimens15),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        color: SQColor.white,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      height: Dimens.dimens50,
                      child: Row(
                        children: [
                          Expanded(
                            child: Container(
                              padding:
                                  EdgeInsets.fromLTRB(Dimens.dimens10, 0, 0, 0),
                              child: Row(
                                children: [
                                  Container(
                                    alignment: Alignment.center,
                                    width: Dimens.dimens24,
                                    height: Dimens.dimens24,
                                    decoration: BoxDecoration(
                                      color: Color(0xff165DFF),
                                      borderRadius: BorderRadius.circular(
                                          Dimens.dimens12),
                                    ),
                                    child: JText(
                                      '1',
                                      color: SQColor.white,
                                    ),
                                  ),
                                  Container(
                                    child: JText(
                                      '  选择排查对象',
                                      color: Color(0xff165DFF),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Expanded(
                            child: Container(
                              child: Row(
                                children: [
                                  Container(
                                    alignment: Alignment.center,
                                    width: Dimens.dimens24,
                                    height: Dimens.dimens24,
                                    decoration: BoxDecoration(
                                      color: Color(0xff165DFF),
                                      borderRadius: BorderRadius.circular(
                                          Dimens.dimens12),
                                    ),
                                    child: JText(
                                      '2',
                                      color: SQColor.white,
                                    ),
                                  ),
                                  Container(
                                    child: JText(
                                      '  选择排查内容',
                                      color: Color(0xff165DFF),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 15),
                      child: ListView.builder(
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: _selPcdxList.length,
                          itemBuilder: (context, index) {
                            return InkWell(
                              onTap: () {
                                Navigator.pushNamed(context, '/SelectPcnr',
                                        arguments: StringUtils.getStr(_selPcdxList[index]['id'].toString()))
                                    .then((value) {
                                  if (value != null) {
                                    setState(() {
                                      List list = value;
                                      List list1 = [];
                                      for (var i = 0; i < list.length; i++) {
                                        if(!EmptyUtils.isForEmpty(list[i]['selControlMeasureList']) && list[i]['selControlMeasureList']['isSel'] == true) {
                                          Map map = {
                                            'dangerSourceId': list[i]
                                            ['dangerSourceId'],
                                            'riskDangerSourceEvaluateId': list[i]
                                            ['riskDangerSourceEvaluateId'],
                                            'controlMeasure': list[i]
                                            ['controlMeasureList'][0],
                                          };
                                          list1.add(map);
                                        }
                                      }
                                      _pcnrList[index][
                                              'hazardInvestigationContentList'] =
                                          list1;
                                    });
                                  }
                                });
                              },
                              child: Column(
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                      color: SQColor.white,
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    padding: EdgeInsets.all(15),
                                    child: Row(
                                      children: [
                                        Expanded(
                                          child: JText(_selPcdxList[index]
                                                  ['riskPointName'] ??
                                              ''),
                                        ),
                                        // JText(
                                        //   _pcnrList[index]['isQuanXuan'] ==
                                        //               null ||
                                        //           _pcnrList[index]['isQuanXuan']
                                        //       ? '已全选'
                                        //       : '不涉及',
                                        //   color: Color(0xff999999),
                                        // ),
                                        Icon(
                                          Icons.arrow_forward_ios_outlined,
                                          size: Dimens.dimens15,
                                          color: SQColor.black_999999,
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    height: 10,
                                    color: Color(0xfff6f6f6),
                                    width: double.infinity,
                                  ),
                                ],
                              ),
                            );
                          }),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Container(
            color: SQColor.white,
            height: Dimens.dimens64,
            child: Row(
              children: [
                Expanded(
                  child: InkWell(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      _currentIndex = 0;
                      _pageController.animateToPage(0,
                          curve: Curves.ease,
                          duration: Duration(milliseconds: 400));
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        color: SQColor.white,
                        border: Border.all(
                          width: 1,
                          color: Color(0xff165DFF),
                        ),
                      ),
                      margin: EdgeInsets.only(
                          left: Dimens.dimens16,
                          right: Dimens.dimens16,
                          top: Dimens.dimens10,
                          bottom: Dimens.dimens10),
                      child: Center(
                        child: JText(
                          '上一步',
                          color: Color(0xff165DFF),
                        ),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: InkWell(
                    onTap: () {
                      for (var i = 0; i < _pcnrList.length; i++) {
                        if (_pcnrList[i]['hazardInvestigationContentList'] == null) {
                          ToastUtils.showToast('请先选择排查内容');
                          return;
                        }
                      }
                      Navigator.pop(context, _pcnrList);
                    },
                    child: Container(
                      margin: EdgeInsets.only(
                          left: Dimens.dimens16,
                          right: Dimens.dimens16,
                          top: Dimens.dimens10,
                          bottom: Dimens.dimens10),
                      color: Color(0xff165DFF),
                      child: Center(
                        child: JText(
                          '完成',
                          color: SQColor.white,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
